﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using Admin.NET.Application.Entity;
using Admin.NET.Core.Service;
using Furion.DatabaseAccessor;
using Furion.FriendlyException;
using Mapster;
using Microsoft.AspNetCore.Http;
using SqlSugar;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace Admin.NET.Application;

/// <summary>
/// 产品入库服务 🧩
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public class WarehousingService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<Warehousing> _warehousingRep;
    private readonly ISqlSugarClient _sqlSugarClient;

    public WarehousingService(SqlSugarRepository<Warehousing> warehousingRep, ISqlSugarClient sqlSugarClient)
    {
        _warehousingRep = warehousingRep;
        _sqlSugarClient = sqlSugarClient;
    }

    /// <summary>
    /// 分页查询产品入库 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("分页查询产品入库")]
    [ApiDescriptionSettings(Name = "Page"), HttpPost]
    public async Task<SqlSugarPagedList<WarehousingOutput>> Page(PageWarehousingInput input)
    {
        input.Keyword = input.Keyword?.Trim();
        var query = _warehousingRep.AsQueryable()
            .WhereIF(!string.IsNullOrWhiteSpace(input.Keyword), u => u.WarehousingNumber.Contains(input.Keyword))
            .WhereIF(!string.IsNullOrWhiteSpace(input.WarehousingNumber), u => u.WarehousingNumber.Contains(input.WarehousingNumber.Trim()))
            .WhereIF(input.StorageLocationId != null, u => u.StorageLocationId == input.StorageLocationId)
            .WhereIF(input.ReservoirId != null, u => u.ReservoirId == input.ReservoirId)
            .WhereIF(input.WarehouseId != null, u => u.WarehouseId == input.WarehouseId)
            .LeftJoin<StorageLocation>((u, storageLocation) => u.StorageLocationId == storageLocation.Id)
            .LeftJoin<Reservoir>((u, storageLocation, reservoir) => u.ReservoirId == reservoir.Id)
            .LeftJoin<Warehouse>((u, storageLocation, reservoir, warehouse) => u.WarehouseId == warehouse.Id)
            .Select((u, storageLocation, reservoir, warehouse) => new WarehousingOutput
            {
                Id = u.Id,
                WarehousingNumber = u.WarehousingNumber,
                CreateTime = u.CreateTime,
                UpdateTime = u.UpdateTime,
                CreateUserId = u.CreateUserId,
                CreateUserName = u.CreateUserName,
                UpdateUserId = u.UpdateUserId,
                UpdateUserName = u.UpdateUserName,
                IsDelete = u.IsDelete,
                StorageLocationId = u.StorageLocationId,
                StorageLocationFkDisplayName = $"{storageLocation.StorageLocationName}",
                ReservoirId = u.ReservoirId,
                ReservoirFkDisplayName = $"{reservoir.ReservoirName}",
                WarehouseId = u.WarehouseId,
                WarehouseFkDisplayName = $"{warehouse.WarehouseName}",
                IsEnable = u.IsEnable,
            });
		return await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 获取产品入库详情 ℹ️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("获取产品入库详情")]
    [ApiDescriptionSettings(Name = "Detail"), HttpGet]
    public async Task<Warehousing> Detail([FromQuery] QueryByIdWarehousingInput input)
    {
        return await _warehousingRep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 增加产品入库 ➕
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("增加产品入库")]
    [ApiDescriptionSettings(Name = "Add"), HttpPost]
    public async Task<long> Add(AddWarehousingInput input)
    {
        var entity = input.Adapt<Warehousing>();
        return await _warehousingRep.InsertAsync(entity) ? entity.Id : 0;
    }

    /// <summary>
    /// 更新产品入库 ✏️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("更新产品入库")]
    [ApiDescriptionSettings(Name = "Update"), HttpPost]
    public async Task Update(UpdateWarehousingInput input)
    {
        var entity = input.Adapt<Warehousing>();
        await _warehousingRep.AsUpdateable(entity)
        .ExecuteCommandAsync();
    }

    /// <summary>
    /// 删除产品入库 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("删除产品入库")]
    [ApiDescriptionSettings(Name = "Delete"), HttpPost]
    public async Task Delete(DeleteWarehousingInput input)
    {
        var entity = await _warehousingRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _warehousingRep.FakeDeleteAsync(entity);   //假删除
        //await _warehousingRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 批量删除产品入库 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("批量删除产品入库")]
    [ApiDescriptionSettings(Name = "BatchDelete"), HttpPost]
    public async Task<int> BatchDelete([Required(ErrorMessage = "主键列表不能为空")]List<DeleteWarehousingInput> input)
    {
        var exp = Expressionable.Create<Warehousing>();
        foreach (var row in input) exp = exp.Or(it => it.Id == row.Id);
        var list = await _warehousingRep.AsQueryable().Where(exp.ToExpression()).ToListAsync();
   
        return await _warehousingRep.FakeDeleteAsync(list);   //假删除
        //return await _warehousingRep.DeleteAsync(list);   //真删除
    }
    
    /// <summary>
    /// 获取下拉列表数据 🔖
    /// </summary>
    /// <returns></returns>
    [DisplayName("获取下拉列表数据")]
    [ApiDescriptionSettings(Name = "DropdownData"), HttpPost]
    public async Task<Dictionary<string, dynamic>> DropdownData(DropdownDataWarehousingInput input)
    {
        var storageLocationIdData = await _warehousingRep.Context.Queryable<StorageLocation>()
            .InnerJoinIF<Warehousing>(input.FromPage, (u, r) => u.Id == r.StorageLocationId)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.StorageLocationName}"
            }).ToListAsync();
        var reservoirIdData = await _warehousingRep.Context.Queryable<Reservoir>()
            .InnerJoinIF<Warehousing>(input.FromPage, (u, r) => u.Id == r.ReservoirId)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.ReservoirName}"
            }).ToListAsync();
        var warehouseIdData = await _warehousingRep.Context.Queryable<Warehouse>()
            .InnerJoinIF<Warehousing>(input.FromPage, (u, r) => u.Id == r.WarehouseId)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.WarehouseName}"
            }).ToListAsync();
        return new Dictionary<string, dynamic>
        {
            { "storageLocationId", storageLocationIdData },
            { "reservoirId", reservoirIdData },
            { "warehouseId", warehouseIdData },
        };
    }
    
    /// <summary>
    /// 导出产品入库记录 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("导出产品入库记录")]
    [ApiDescriptionSettings(Name = "Export"), HttpPost, NonUnify]
    public async Task<IActionResult> Export(PageWarehousingInput input)
    {
        var list = (await Page(input)).Items?.Adapt<List<ExportWarehousingOutput>>() ?? new();
        if (input.SelectKeyList?.Count > 0) list = list.Where(x => input.SelectKeyList.Contains(x.Id)).ToList();
        return ExcelHelper.ExportTemplate(list, "产品入库导出记录");
    }
    
    /// <summary>
    /// 下载产品入库数据导入模板 ⬇️
    /// </summary>
    /// <returns></returns>
    [DisplayName("下载产品入库数据导入模板")]
    [ApiDescriptionSettings(Name = "Import"), HttpGet, NonUnify]
    public IActionResult DownloadTemplate()
    {
        return ExcelHelper.ExportTemplate(new List<ExportWarehousingOutput>(), "产品入库导入模板", (_, info) =>
        {
            if (nameof(ExportWarehousingOutput.StorageLocationFkDisplayName) == info.Name) return _warehousingRep.Context.Queryable<StorageLocation>().Select(u => $"{u.StorageLocationName}").Distinct().ToList();
            if (nameof(ExportWarehousingOutput.ReservoirFkDisplayName) == info.Name) return _warehousingRep.Context.Queryable<Reservoir>().Select(u => $"{u.ReservoirName}").Distinct().ToList();
            if (nameof(ExportWarehousingOutput.WarehouseFkDisplayName) == info.Name) return _warehousingRep.Context.Queryable<Warehouse>().Select(u => $"{u.WarehouseName}").Distinct().ToList();
            return null;
        });
    }
    
    /// <summary>
    /// 导入产品入库记录 💾
    /// </summary>
    /// <returns></returns>
    [DisplayName("导入产品入库记录")]
    [ApiDescriptionSettings(Name = "Import"), HttpPost, NonUnify, UnitOfWork]
    public IActionResult ImportData([Required] IFormFile file)
    {
        lock (this)
        {
            var stream = ExcelHelper.ImportData<ImportWarehousingInput, Warehousing>(file, (list, markerErrorAction) =>
            {
                _sqlSugarClient.Utilities.PageEach(list, 2048, pageItems =>
                {
                    // 链接 所属库位
                    var storageLocationIdLabelList = pageItems.Where(x => x.StorageLocationFkDisplayName != null).Select(x => x.StorageLocationFkDisplayName).Distinct().ToList();
                    if (storageLocationIdLabelList.Any()) {
                        var storageLocationIdLinkMap = _warehousingRep.Context.Queryable<StorageLocation>().Where(u => storageLocationIdLabelList.Contains($"{u.StorageLocationName}")).ToList().ToDictionary(u => $"{u.StorageLocationName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.StorageLocationId = storageLocationIdLinkMap.GetValueOrDefault(e.StorageLocationFkDisplayName ?? "");
                            if (e.StorageLocationId == null) e.Error = "所属库位链接失败";
                        });
                    }
                    // 链接 所属库区
                    var reservoirIdLabelList = pageItems.Where(x => x.ReservoirFkDisplayName != null).Select(x => x.ReservoirFkDisplayName).Distinct().ToList();
                    if (reservoirIdLabelList.Any()) {
                        var reservoirIdLinkMap = _warehousingRep.Context.Queryable<Reservoir>().Where(u => reservoirIdLabelList.Contains($"{u.ReservoirName}")).ToList().ToDictionary(u => $"{u.ReservoirName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.ReservoirId = reservoirIdLinkMap.GetValueOrDefault(e.ReservoirFkDisplayName ?? "");
                            if (e.ReservoirId == null) e.Error = "所属库区链接失败";
                        });
                    }
                    // 链接 所属仓库
                    var warehouseIdLabelList = pageItems.Where(x => x.WarehouseFkDisplayName != null).Select(x => x.WarehouseFkDisplayName).Distinct().ToList();
                    if (warehouseIdLabelList.Any()) {
                        var warehouseIdLinkMap = _warehousingRep.Context.Queryable<Warehouse>().Where(u => warehouseIdLabelList.Contains($"{u.WarehouseName}")).ToList().ToDictionary(u => $"{u.WarehouseName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.WarehouseId = warehouseIdLinkMap.GetValueOrDefault(e.WarehouseFkDisplayName ?? "");
                            if (e.WarehouseId == null) e.Error = "所属仓库链接失败";
                        });
                    }
                    
                    // 校验并过滤必填基本类型为null的字段
                    var rows = pageItems.Where(x => {
                        if (!string.IsNullOrWhiteSpace(x.Error)) return false;
                        if (x.StorageLocationId == null){
                            x.Error = "所属库位不能为空";
                            return false;
                        }
                        if (!string.IsNullOrWhiteSpace(x.Error)) return false;
                        if (x.ReservoirId == null){
                            x.Error = "所属库区不能为空";
                            return false;
                        }
                        if (!string.IsNullOrWhiteSpace(x.Error)) return false;
                        if (x.WarehouseId == null){
                            x.Error = "所属仓库不能为空";
                            return false;
                        }
                        if (!string.IsNullOrWhiteSpace(x.Error)) return false;
                        if (x.IsEnable == null){
                            x.Error = "是否启用不能为空";
                            return false;
                        }
                        return true;
                    }).Adapt<List<Warehousing>>();
                    
                    var storageable = _warehousingRep.Context.Storageable(rows)
                        .SplitError(it => it.Item.WarehousingNumber?.Length > 32, "入库编号长度不能超过32个字符")
                        .SplitInsert(_ => true)
                        .ToStorage();
                    
                    storageable.BulkCopy();
                    storageable.BulkUpdate();
                    
                    // 标记错误信息
                    markerErrorAction.Invoke(storageable, pageItems, rows);
                });
            });
            
            return stream;
        }
    }
}
